package ru.minidoc.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ru.minidoc.dao.UserDao;
import ru.minidoc.model.User;
import ru.minidoc.model.json.UserData;
import ru.minidoc.model.json.UserList;

@Controller
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/user/read.action", method = RequestMethod.GET)
    public @ResponseBody
    UserList read() {
        List<User> userList = userDao.getUserList();
        return new UserList(userList.size(), userList);
    }

    @RequestMapping(value = "/user/create.action", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Integer> create(@RequestBody UserData userList) {
        Map<String, Integer> result = new HashMap<String, Integer>();
        Integer id = userDao.create(userList.rows);
        result.put("id", id);
        return result;
    }

    @RequestMapping(value = "/user/update.action", method = RequestMethod.POST)
    public @ResponseBody
    void update(@RequestBody UserData userList) {
        userDao.update(userList.rows);
    }

    @RequestMapping(value = "/user/destroy.action", method = RequestMethod.POST)
    public @ResponseBody
    String destroy(@RequestBody Map<String, Integer> rows) {
        userDao.delete(new User(rows.get("rows")));
        return "1";
    }
}
